package com.supreme.gatewayserver.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;

@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress localAddress = request.getLocalAddress();
        InetSocketAddress remoteAddress = request.getRemoteAddress();

        URI uri = request.getURI();
        String uriPath = uri.getPath();
        String uriRawPath = uri.getRawPath();

        HttpHeaders requestHeaders = request.getHeaders();
        String authorization = requestHeaders.getFirst("Authorization");

        System.out.printf("CustomGlobalFilter:\nlocalAddress:\t\t%s\nremoteAddress:\t\t%s\nuriPath:\t\t%s\nuriRawPath:\t\t%s\nauthorization:\t\t%s\n",
                localAddress, remoteAddress, uriPath, uriRawPath, authorization);

        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String name = queryParams.getFirst("name");
        if (name != null && !name.equals("admin")) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);

            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
